import { createRouter,createWebHashHistory } from 'vue-router'
import { ref } from 'vue' 
import { sidemenu } from '~/api/admin/manager.js'
//前端模板
import Home from '~/views/front/index/list.vue'
import Login from '~/views/front/login.vue'
//后端模板
import Admin from '~/views/admin/layouts/admin.vue'
import AdminIndex from '~/views/admin/home.vue'
import adminLogin from '~/views/admin/login.vue'
import AdminGoods from '~/views/admin/goods/list.vue'
import AdminImage from '~/views/admin/iamge/list.vue'
//404路径错误页面
import NotFound from '~/views/404.vue'

/* const routes = [
  { path: '/', 
    component: Home,
    meta:{title:'网站首页'} 
  },
  { path: '/login', component: Login,meta:{title:'网站登录页'} },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
  { path :'/admin/login',component:adminLogin,meta:{title:'后台登录页'}},
  { path: '/admin', 
    component: Admin,
    children:[
      {path: '/admin', component: AdminIndex,meta:{title:'后台首页'},},
      {path: '/goods/list', component: AdminGoods,meta:{title:'商品管理'},},
      {path: '/image/list', component: AdminImage,meta:{title:'图集管理'},},
    ]
  },
] */

//默认路由，所有用户共享
const routes = [
  { path: '/', 
    component: Home,
    meta:{title:'网站首页'} 
  },
  { path: '/login', component: Login,meta:{title:'网站登录页'} },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
  { path :'/admin/login',component:adminLogin,meta:{title:'后台登录页'}},
  { path: '/admin', component: Admin,name:'admin'},
]

//动态路由，用于匹配菜单动态添加
const asyncRoutes = [
  {path: '/admin',name:'/admin', component: AdminIndex,meta:{title:'后台首页'},},
  {path: '/goods/list',name:'/goods/list', component: AdminGoods,meta:{title:'商品管理'},},
  {path: '/image/list',name:'/image/list', component: AdminImage,meta:{title:'图集管理'},},
]

/* const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

export default router */

export const router = createRouter({
  history: createWebHashHistory(),
  routes,
})



//动态添加路由的方法
export function addRoutes(menus){
  //是否有新的路由
  let hasNewRoutes = false
  //递归
  const findAndAddRoutesByMenus = (arr)=>{
    arr.forEach(e=>{
      let item = asyncRoutes.find(o=>o.path == e.front_path)
      if(item && !router.hasRoute(item.path)){
        router.addRoute('admin',item)
        hasNewRoutes = true
      }
      if(e.child && e.child.length > 0){
        findAndAddRoutesByMenus(e.child)
      }
    })
  }

  findAndAddRoutesByMenus(menus)
  
  return hasNewRoutes
}